//
//  PywTextFieldView.m
//  PywSdk2.2_Test
//
//  Created by smallwave on 16/7/28.
//  Copyright © 2016年 yyft. All rights reserved.
//

#import "PywTextFieldView.h"
#import "PywTextField.h"
#import "PywMasonry.h"
#import "UIImage+Pyw.h"
#import "PywCommonManager.h"

#define kPhoneLenght 11
#define kPasswordMaxLenght 12

@interface PywTextFieldView  ()<UITextFieldDelegate>

@property (nonatomic, strong) PywTextField  *textField;         // 文本输入框
@property (nonatomic, strong) UIView        *vLine;             // 竖直分隔线
@property (nonatomic, strong) UIView        *bottomLine;        // 底部边框线

@property (nonatomic, copy) NSString        *leftImgName;       // 文本输入框 textField.leftView 的图片名称
@property (nonatomic, copy) NSString        *placeholder;       // 文本输入框 textField.placeholder 提示文字
@property (nonatomic, assign) BOOL          showLine;           // 文本输入框 与 按钮 之间的竖直分隔线
@property (nonatomic, copy) NSString        *btnTitle;          // 按钮的标题
@property (nonatomic, copy) NSString        *btnNormalImgName;  // 按钮默认背景图片名称
@property (nonatomic, copy) NSString        *btnSelectedImgName;// 按钮选中背景图片名称
@property (nonatomic,assign) NSInteger      textFieldInputType; // 文本输入框的输入类型

@end

@implementation PywTextFieldView

#pragma mark - Class Method
/// 手机号码输入框
+ (instancetype)phoneTextFieldWithLeftImg:(NSString *)leftImg
                          TextPlaceholder:(NSString *)placeholder{
    return [[PywTextFieldView alloc] initWithTextLeftImg:leftImg
                                         TextPlaceholder:placeholder
                                                ShowLine:NO
                                                Delegate:nil
                                             ButtonTitle:nil
                                         ButtonNormalImg:nil
                                       ButtonSelectedImg:nil
                                      TextFieldInputType:TextFieldType_Phone];
}
/// 手机号码/游戏账号输入框
+ (instancetype)phoneOrAccountTextFieldWithLeftImg:(NSString *)leftImg
                                   TextPlaceholder:(NSString *)placeholder{
    return [[PywTextFieldView alloc] initWithTextLeftImg:leftImg
                                         TextPlaceholder:placeholder
                                                ShowLine:NO
                                                Delegate:nil
                                             ButtonTitle:nil
                                         ButtonNormalImg:nil
                                       ButtonSelectedImg:nil
                                      TextFieldInputType:TextFieldType_PhoneOrAccount];
}
/// 验证码输入框
+ (instancetype)validCodeTextFieldWithLeftImg:(NSString *)leftImg
                              TextPlaceholder:(NSString *)placeholder
                                     Delegate:(id<PywTextFieldViewDelegate>)delegate
                                  ButtonTitle:(NSString *)buttonTitle{
    return [[PywTextFieldView alloc] initWithTextLeftImg:leftImg
                                         TextPlaceholder:placeholder
                                                ShowLine:YES
                                                Delegate:delegate
                                             ButtonTitle:buttonTitle
                                         ButtonNormalImg:nil
                                       ButtonSelectedImg:nil
                                      TextFieldInputType:TextFieldType_SmsCode];
}
/// 密码输入框
+ (instancetype)passwordTextFieldWithLeftImg:(NSString *)leftImg
                             TextPlaceholder:(NSString *)placeholder
                             ButtonNormalImg:(NSString *)normalImg
                           ButtonSelectedImg:(NSString *)selectedImg{
    return [[PywTextFieldView alloc] initWithTextLeftImg:leftImg
                                         TextPlaceholder:placeholder
                                                ShowLine:NO
                                                Delegate:nil
                                             ButtonTitle:nil
                                         ButtonNormalImg:normalImg
                                       ButtonSelectedImg:selectedImg
                                      TextFieldInputType:TextFieldType_Password];
}

#pragma mark - Custom init method
/**
 *  文本输入框的View
 *
 *  @param leftImg     文本输入框 textField.leftView 的图片名称
 *  @param placeholder 文本输入框 textField.placeholder 提示文字
 *  @param showLine    竖直分隔线是BOOL值
 *                     （1）YES：验证码输入框（参数：normalImg和selectedImg传入nil）；
 *                     （2） NO：密码输入框（参数：buttonTitle传入nil） 或 手机号输入框（参数：buttonTitle、normalImg和selectedImg传入nil）
 *  @param delegate    Delegate
 *  @param buttonTitle 按钮的标题
 *  @param normalImg   按钮默认背景图片名称
 *  @param selectedImg 按钮选中背景图片名称
 *
 *  @return 返回一个自定义的文本输入框
 */
- (instancetype)initWithTextLeftImg:(NSString *)leftImg
                    TextPlaceholder:(NSString *)placeholder
                           ShowLine:(BOOL)showLine
                           Delegate:(id<PywTextFieldViewDelegate>)delegate
                        ButtonTitle:(NSString *)buttonTitle
                    ButtonNormalImg:(NSString *)normalImg
                  ButtonSelectedImg:(NSString *)selectedImg
                 TextFieldInputType:(NSInteger)inputType{
    
    self = [super init];
    if (self) {
        self.leftImgName = leftImg;
        self.placeholder = placeholder;
        self.showLine = showLine;
        self.delegate = delegate;
        self.btnTitle = buttonTitle;
        self.btnNormalImgName = normalImg;
        self.btnSelectedImgName = selectedImg;
        self.textFieldInputType = inputType;
        
        [self addSubviewAndLayoutSubviews];
    }
    return self;
}
- (void)addSubviewAndLayoutSubviews{
    
    __weak typeof(self) wSelf = self;
    if (self.showLine == YES && self.btnTitle.length > 0) { // 验证码输入框约束布局
        [self addSubview:self.textField];
        [self addSubview:self.vLine];
        [self addSubview:self.operationBtn];
        [self addSubview:self.bottomLine];
        
        [self.textField mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.left.top.equalTo(wSelf);
            make.bottom.equalTo(wSelf.bottomLine.mas_top);
            make.right.equalTo(wSelf.vLine.mas_left);
        }];
        
        [self.vLine mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.centerY.equalTo(wSelf.mas_centerY);
            make.left.equalTo(wSelf.textField.mas_right);
            make.height.equalTo(wSelf.mas_height).multipliedBy(0.6);
            make.width.equalTo(@1);
        }];
        
        CGFloat buttonW = [self changeDeviceButtonWidth:80];
        [self.operationBtn mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.left.equalTo(wSelf.vLine.mas_right);
            make.top.bottom.equalTo(wSelf.textField);
            make.right.equalTo(wSelf.mas_right).offset(-5);
            make.width.equalTo(@(buttonW));
        }];
        
        [self.bottomLine mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.height.equalTo(@1);
            make.left.right.bottom.equalTo(wSelf);
        }];
    }else if(self.showLine == NO ) {
        if (self.btnNormalImgName.length > 0
            || self.btnSelectedImgName.length > 0) { // 密码输入框约束布局
            [self addSubview:self.textField];
            [self addSubview:self.operationBtn];
            [self addSubview:self.bottomLine];
            
            [self.textField mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.left.top.equalTo(wSelf);
                make.bottom.equalTo(wSelf.bottomLine.mas_top);
                make.right.equalTo(wSelf.operationBtn.mas_left);
            }];
            
            [self.operationBtn mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.centerY.equalTo(wSelf.mas_centerY);
                make.left.equalTo(wSelf.textField.mas_right);
                make.right.equalTo(wSelf.mas_right).offset(-5);
                make.width.height.equalTo(@40);
            }];
            
            [self.bottomLine mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.left.right.bottom.equalTo(wSelf);
                make.top.equalTo(wSelf.textField.mas_bottom);
                make.height.equalTo(@1);
            }];
        }else{  // 手机号码输入框的约束布局
            [self addSubview:self.textField];
            [self addSubview:self.bottomLine];
            
            [self.textField mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.top.left.right.equalTo(wSelf);
                make.bottom.equalTo(wSelf.bottomLine.mas_top);
            }];
            
            [self.bottomLine mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.top.equalTo(wSelf.textField.mas_bottom);
                make.left.right.equalTo(wSelf.textField);
                make.height.equalTo(@1);
                make.bottom.equalTo(wSelf.mas_bottom);
            }];
        }
    }
}
/**
 *  根据设备不同来确定按钮宽度
 */
- (CGFloat)changeDeviceButtonWidth:(CGFloat)btnWidth{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    
    if (width < height) {
        btnWidth = (width / 320) * btnWidth;
    }else{
        btnWidth = (width / 568) * btnWidth;
    }
    return btnWidth;
}

#pragma mark - Event method
- (void)operationEvent:(UIButton *)btn{
    btn.selected = !btn.selected;
    self.operationBtn.selected = btn.selected;
    
    if (self.showLine == NO) {  // 此时，为密码输入框
        // 设置Text显示为  明文/密文
        self.textField.secureTextEntry = !self.textField.secureTextEntry;
        // 切换明文/密文显示末尾空白的 处理
        NSString* text = self.textField.text;
        self.textField.text = @"";
        self.textField.text = text;
    }
    
    if ([self.delegate respondsToSelector:@selector(textFieldView:buttonEvent:)]) {
        [self.delegate textFieldView:self buttonEvent:btn];
    }
    
}

#pragma mark - lazy method
/*
 *  文本输入框
 */
- (PywTextField *)textField{
    if (!_textField) {
        _textField = [PywTextField inputTextFieldWithLeftImgName:self.leftImgName
                                                     placeholder:self.placeholder
                                                    textFontSize:13];
        _textField.backgroundColor = [UIColor clearColor];
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.delegate = self;
        [_textField sizeToFit];
    }
    return _textField;
}
/*
 *  竖直分隔线
 */
- (UIView *)vLine{
    if (!_vLine) {
        _vLine = [[UIView alloc] init];
        _vLine.backgroundColor = [UIColor lightGrayColor];
    }
    return _vLine;
}
/*
 *  操作按钮
 */
- (UIButton *)operationBtn{
    if (!_operationBtn) {
        _operationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _operationBtn.backgroundColor = [UIColor clearColor];
        
        CGFloat fontSize = [[PywCommonManager manager] changeDeviceTextFontSize:13];
        _operationBtn.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        
        if (_showLine == YES) {
            [_operationBtn setTitleColor:RGB(252, 177, 14, 1) forState:UIControlStateNormal];
            [_operationBtn setTitle:self.btnTitle forState:UIControlStateNormal];
        }else{
            self.vLine.hidden = YES;
            [_operationBtn setImage:[UIImage imageWithName:self.btnNormalImgName] forState:UIControlStateNormal];
            [_operationBtn setImage:[UIImage imageWithName:self.btnSelectedImgName] forState:UIControlStateSelected];
        }
        
        [_operationBtn addTarget:self action:@selector(operationEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_operationBtn sizeToFit];
        [_operationBtn setAccessibilityIdentifier:@"common_getcode"];
    }
    return _operationBtn;
}
/*
 *  底部边框线
 */
- (UIView *)bottomLine{
    if (!_bottomLine) {
        _bottomLine = [[UIView alloc] init];
        _bottomLine.backgroundColor = [UIColor lightGrayColor];
    }
    return _bottomLine;
}

#pragma mark - UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    // 按回车键可以改变
    if ([string isEqualToString:@"\n"]) {
        return NO;
    }
    //string就是此时输入的那个字符
    if (self.showLine == NO) { // 此时为密码输入框 或 手机号码输入框
        // 获得输入框的内容
        switch (self.textFieldInputType) {
            case TextFieldType_Password:// 密码输入框
            {
                NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
                if (self.textField == textField) {
                    if (toBeString.length > kPasswordMaxLenght) {
                        textField.text = [toBeString substringToIndex:kPasswordMaxLenght];
                        return NO;
                    }
                }
            }
                break;
            case TextFieldType_Phone:// 手机号码输入框
            {
                NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
                if (self.textField == textField) {
                    if (toBeString.length > kPhoneLenght) {
                        textField.text = [toBeString substringToIndex:kPhoneLenght];
                        return NO;
                    }
                }
            }
                break;
            case TextFieldType_PhoneOrAccount://手机号|游戏账号输入框
            {
                NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
                if (textField == _textField) {
                    textField.text = toBeString;
                    return NO;
                }
            }
                break;
                
            default:
                break;
        }
        
    }else{// 此时为验证码输入框
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (textField == _textField) {
            textField.text = toBeString;
            return NO;
        }
    }
    
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self.textField resignFirstResponder];
}

#pragma mark - Setter & Getter
- (void)setText:(NSString *)text{
    self.textField.text = text; // 设置校验验证码失败，清空文本输入内容
}
- (NSString *)text{
    return self.textField.text;
}
- (void)setAccessibilityId:(NSString *)accessibilityId
{
    [self.textField setAccessibilityIdentifier:accessibilityId];
}
- (NSString *)accessibilityId
{
    return self.textField.accessibilityIdentifier;
}
// 设置密码输入框  明/密文显示
- (void)setSecureTextEntry:(BOOL)secureTextEntry{
    _textField.secureTextEntry = secureTextEntry;
}
- (BOOL)isSecureTextEntry{
    return _textField.secureTextEntry;
}
- (void)dealloc{
    self.leftImgName = nil;
    self.placeholder = nil;
    self.showLine = NO;
    self.delegate = nil;
    self.btnTitle = nil;
    self.btnNormalImgName = nil;
    self.btnSelectedImgName = nil;
}

@end
